import React, {useEffect, useState} from "react";
import axios from "axios";

const request = async url => {
    const resp = await axios.get(url);
    const data = resp.data;
    if(data.code !== 200) {
        alert('服务器开小差了');
        return {};
    }
    return data.data;
};

const useUser = (id) => {
    const [user, setUser] = useState({});
    const [loading, setLoading] = useState();
    const getUser = async () => {
        setLoading(true);
        const user = await request(`https://xiaozhu.run/api/user/${id}`);
        setUser(user);
        setLoading(false);
    };
    useEffect(() => {
        getUser();
    }, [id]);
    return [user, loading];
}

const GetUser = () => {
    //useState 方法实现异步请求
    // const [user, setUser] = useState({});
    // const [id, setId] = useState(9527);

    // const getUser = async () => {
    //     const user = await request(`https://xiaozhu.run/api/user/${id}`);
    //     setUser(user);
    // };

    // useEffect(() => getUser(), [id]);

    const [id, setId] = useState(9527);
    const [user, loading] = useUser(id);

    return (
        <div>
            <button onClick={() => setId(id + 1)}>
                Get User {id}
            </button>
            <p>{loading && 'loading...'}</p>
            <div>Email:{user.email}</div>
            <div>Name:{user.username}</div>
        </div>
    )
}

export default GetUser;